import React, { useEffect, useRef, useState } from "react";

const useCountsSix = (initTime = 60) => {
  const timer = useRef(null);
  const [countDown, setCountDown] = useState(initTime);
  const [isRuning, setIsRuning] = useState(false);

  const startCountDown = () => {
    if (!isRuning) {
      setIsRuning(true);
      timer.current = setInterval(() => {
        setCountDown((pre) => {
          if (pre < 1) {
            clearInterval(timer.current);
            setIsRuning(false);
            return initTime;
          }
          return pre - 1;
        });
      }, 1000);
    }
  };

  useEffect(() => {
    return () => {
      if (timer.current) {
        clearInterval(timer.current);
      }
    };
  }, []);

  return { countDown, isRuning, startCountDown };
};

export default useCountsSix;
